package com.eairlv.utils.validator.user;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.eairlv.utils.MSInterceptorProperties;
import com.eairlv.utils.annotation.AccessUser;
import com.eairlv.utils.config.MSInterceptor;
import com.eairlv.utils.utils.HttpUtil;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;

/**
 * @author eairlv
 * @description
 * @date 11:26 2019/8/27
 */
public class UserValidator {

    /**
     * 用户装载方式
     */
    public static final String HEADER = "header";

    /**
     * 用户的Header
     */
    public static final String USER_INFORMATION = "User-Information";

    /**
     * 用户信息验证器
     *
     * @param handler
     * @return
     */
    public static Boolean valid(HttpServletRequest request, HandlerMethod handler, MSInterceptorProperties properties) {
        AccessUser classAnnotation = handler.getClass().getAnnotation(AccessUser.class);
        AccessUser methodAnnotation = handler.getMethodAnnotation(AccessUser.class);
        if (ObjectUtil.isNull(userInformation(properties.getUserPayload(), request))) {
            if (methodAnnotation != null) {
                return !methodAnnotation.user();
            } else if (classAnnotation != null) {
                return !classAnnotation.user();
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 装载用户信息
     *
     * @param userPayload
     * @param request
     */
    private static UserInformation userInformation(String userPayload, HttpServletRequest request) {
        UserInformation userInformation;
        String userInfo = HttpUtil.getUserInfoFromHeader(request);
        if (StrUtil.isNotBlank(userInfo)) {
            userInformation = JSON.parseObject(userInfo, UserInformation.class);
        } else {
            userInformation = MSInterceptor.USER_INFORMATION.get();
        }
        if (!userPayload.equals(HEADER) && userInformation != null) {
            MSInterceptor.USER_INFORMATION.set(userInformation);
        }
        if (userInformation != null && userInformation.getUserId() != null) {
            return userInformation;
        } else {
            return null;
        }
    }
}
